import Axios from 'axios';

const service = Axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    withCredentials: true,
    timeout: 1000 * 60 * 5
});

// 处理频繁请求
let pending = [];
let cancelToken = Axios.CancelToken;
let removePending = (config) => {
    for (let p in pending) {
        if (pending[p].u === config.url + '&' + config.method) {
            pending[p].f();
            pending.splice(p, 1);
        }
    }
};


// 拦截请求
service.interceptors.request.use(config => {
    // 频繁请求
    removePending(config);
    config.cancelToken = new cancelToken((c) => {
        pending.push({u: config.url + '&' + config.method, f: c});
    });
    // 头信息配置
    config.headers.post['Content-Type'] = 'application/json';
    return config;
}, err => {
    return Promise.reject(err);
});

// 拦截响应
service.interceptors.response.use(res => {
    removePending(res.config);
    return res.data;
}, err => {
    return Promise.reject(err);
});

export default service;